package com.heima.search.service.impl;

import com.heima.search.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class RedisServiceImpl implements RedisService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private String preFix = "ld:search:word:id:";
    /**
     * 异步保存搜索记录
     * @param userId
     * @param equipmentId
     * @param searchWords
     */
    @Async("taskExecutor")
    @Override
    public void saveSearchWord(Integer userId, String equipmentId, String searchWords) {

//      生成key的方法
        String key = getKey(userId,equipmentId);
        log.info("key=={}",key);
//        把关键词存入Redis
        redisTemplate.opsForZSet().incrementScore(key,searchWords,1);
//        给key设置有效期
        redisTemplate.expire(key,7, TimeUnit.DAYS);

    }

    @Override
    public Set<String> getSearchWord(Integer userId, String equipmentId) {
        String key = getKey(userId, equipmentId);
        Set<String> set = redisTemplate.opsForZSet().reverseRange(key, 0, -1);
        return set;
    }

    @Override
    public void delSearchWord(Integer userId, String equipmentId, String searchWord) {
        String key = getKey(userId, equipmentId);
        redisTemplate.opsForZSet().remove(key,searchWord);
    }

    private String getKey(Integer userId, String equipmentId) {
        if(userId != null && userId!=0){
            return preFix + userId;
        }
        return preFix + equipmentId;
    }
}
